//
//  DatePickerView.m
//  时间选择器_test_2
//
//  Created by 1234 on 14-12-25.
//  Copyright (c) 2014年 test. All rights reserved.
//

#import "DatePickerView.h"

@interface DatePickerView ()<UIPickerViewDelegate,UIPickerViewDataSource>


@property (nonatomic,weak) UIView *toolBar;
@property (nonatomic,weak) UIPickerView *pickViewList;


@property (nonatomic,strong) NSMutableArray *yearArray;
@property (nonatomic,strong) NSMutableArray *monthArray;
@property (nonatomic,strong) NSMutableArray *daysArray;
@property (nonatomic,strong) NSMutableArray *hoursArray;
@property (nonatomic,strong) NSMutableArray *minutesArray;

@property (nonatomic,assign) NSInteger currentMonth;
@property (nonatomic,assign) NSInteger selectedYearRow;
@property (nonatomic,assign) NSInteger selectedMonthRow;
@property (nonatomic,assign) NSInteger selectedDayRow;
@property (nonatomic,assign) NSInteger selectedHourRow;
@property (nonatomic,assign) NSInteger selectedMinRow;


@end

@implementation DatePickerView
{
    CGFloat widths;
    CGFloat heights;
    TimeType tTypes;
    NSString *titles;
}

-(id)initWithWidth:(float)width Height:(float)height TimeType:(TimeType)tType WithTitle:(NSString*)title{
    self = [super init];
    if (self)
	{
        widths = width;
        heights = height;
        tTypes = tType;
        titles = title;
        
        [self setupSubViews];
        
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        widths = HARDWARE_SCREEN_WIDTH;
        heights = 216.0f;
        tTypes = timeDetail;
        titles = @"";
        [self setupSubViews];
    }
    return self;
}

- (NSMutableArray *)yearArray{
    if (_yearArray == nil) {
        _yearArray = [NSMutableArray array];
    }
    return _yearArray;
}

- (NSMutableArray *)monthArray{
    if (_monthArray == nil) {
        _monthArray = [NSMutableArray array];
    }
    return _monthArray;
}

- (NSMutableArray *)daysArray{
    if (_daysArray == nil) {
        _daysArray = [NSMutableArray array];
    }
    return _daysArray;
}

- (NSMutableArray *)hoursArray{
    if (_hoursArray == nil) {
        _hoursArray = [NSMutableArray array];
    }
    return _hoursArray;
}

- (NSMutableArray *)minutesArray{
    if (_minutesArray == nil) {
        _minutesArray = [NSMutableArray array];
    }
    return _minutesArray;
}

- (void)setupSubViews
{
    
    self.backgroundColor = WhiteColor;
    
    UIView *toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, widths, 40)];
    toolBar.backgroundColor = RGBCOLORWITH16COLOR(0x3899e8);
    [self addSubview:toolBar];
    self.toolBar = toolBar;

    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0];
    [leftButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 80, 40);
    [leftButton addTarget:self action:@selector(actionCancel) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.toolBar addSubview:leftButton];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftButton.frame), 0, widths - 160, 40)];
    titleLabel.font = [UIFont systemFontOfSize:16.0];
    titleLabel.textColor = [UIColor blackColor];
    [self.toolBar addSubview:titleLabel];
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0];
    [rightButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    rightButton.frame = CGRectMake(widths - 80, 0, 80, 40);
    [rightButton addTarget:self action:@selector(actionDone) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.toolBar addSubview:rightButton];

    UIPickerView *pickList = [[UIPickerView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(self.toolBar.frame),widths - 20,heights - CGRectGetMaxY(self.toolBar.frame))];
    pickList.backgroundColor = ClearColor;
    pickList.showsSelectionIndicator = YES;//在当前选择上显示一个透明窗口
    pickList.delegate = self;
    pickList.dataSource = self;
    self.pickViewList = pickList;
    
    [self addSubview:pickList];
    
    [self loadDate];

}
- (void)loadDate
{
    
    [self.yearArray removeAllObjects];
    [self.monthArray removeAllObjects];
    [self.daysArray removeAllObjects];
    [self.hoursArray removeAllObjects];
    [self.minutesArray removeAllObjects];
    
    // PickerView -  Years data
    for (int i = 1970; i <= 2050 ; i++)
    {
        [self.yearArray addObject:[NSString stringWithFormat:@"%d",i]];
    }
    
    // PickerView -  Months data
    for (int i = 1; i <= 12 ; i++)
    {
        [self.monthArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
    
    // PickerView -  Days data
    for (int i = 1; i <= 31; i++)
    {
        [self.daysArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
    
    // PickerView -  Hours data
    for (int i = 0; i < 24 ; i++)
    {
        [self.hoursArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
    
    // PickerView -  Mins data
    self.minutesArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 60; i++)
    {
        [self.minutesArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }

    NSDate *curDate = [NSDate date];
    [self viewLoad:curDate];
}

-(void)viewLoad:(NSDate *)date{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // Get Current Year
    [formatter setDateFormat:@"yyyy"];
    NSString *currentYearString = [formatter stringFromDate:date];
    
    // Get Current  Month
    [formatter setDateFormat:@"MM"];
    NSString *currentMonthString = [formatter stringFromDate:date];
    // Get Current  Date
    [formatter setDateFormat:@"dd"];
    NSString *currentDateString = [formatter stringFromDate:date];
    
    
    if (tTypes==timeAndDateDetail) {//timeDetail
        // Get Current  Hour
        [formatter setDateFormat:@"HH"];
        NSString *currentHourString = [formatter stringFromDate:date];
        
        // Get Current  Minutes
        [formatter setDateFormat:@"mm"];
        NSString *currentMinutesString = [formatter stringFromDate:date];
        
        // PickerView - Default Selection as per current Date
        [self.pickViewList selectRow:[self.yearArray indexOfObject:currentYearString] inComponent:0 animated:YES];
        [self.pickViewList selectRow:[self.monthArray indexOfObject:currentMonthString] inComponent:1 animated:YES];
        [self.pickViewList selectRow:[self.daysArray indexOfObject:currentDateString] inComponent:2 animated:YES];
        [self.pickViewList selectRow:[self.hoursArray indexOfObject:currentHourString] inComponent:3 animated:YES];
        [self.pickViewList selectRow:[self.minutesArray indexOfObject:currentMinutesString] inComponent:4 animated:YES];
        self.selectedMonthRow = [self.monthArray indexOfObject:currentMonthString];
        self.selectedHourRow = [self.hoursArray indexOfObject:currentHourString];
        self.selectedMinRow = [self.minutesArray indexOfObject:currentMinutesString];
        self.selectedYearRow = [self.yearArray indexOfObject:currentYearString];
        self.selectedDayRow = [self.daysArray indexOfObject:currentDateString];
        
    }else if(tTypes==timeChinese){//timeChinese
        
        //代码暂未添加
        
    }else if (tTypes == dateDetail){//dateDetail
        
        // PickerView - Default Selection as per current Date
        [self.pickViewList selectRow:[self.yearArray indexOfObject:currentYearString] inComponent:0 animated:YES];
        [self.pickViewList selectRow:[self.monthArray indexOfObject:currentMonthString] inComponent:1 animated:YES];
        [self.pickViewList selectRow:[self.daysArray indexOfObject:currentDateString] inComponent:2 animated:YES];
        self.selectedMonthRow = [self.monthArray indexOfObject:currentMonthString];
        self.selectedYearRow = [self.yearArray indexOfObject:currentYearString];
        self.selectedDayRow = [self.daysArray indexOfObject:currentDateString];
    } else if (tTypes == timeDetail){
        [formatter setDateFormat:@"HH"];
        NSString *currentHourString = [formatter stringFromDate:date];
        
        // Get Current  Minutes
        [formatter setDateFormat:@"mm"];
        NSString *currentMinutesString = [formatter stringFromDate:date];
        
        // PickerView - Default Selection as per current Date
        [self.pickViewList selectRow:[self.hoursArray indexOfObject:currentHourString] inComponent:0 animated:YES];
        [self.pickViewList selectRow:[self.minutesArray indexOfObject:currentMinutesString] inComponent:1 animated:YES];
        self.selectedHourRow = [self.hoursArray indexOfObject:currentHourString];
        self.selectedMinRow = [self.minutesArray indexOfObject:currentMinutesString];
    } else {
        
    }
    
}

#pragma mark -
#pragma mark - UIPickerViewDelegate

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (tTypes==timeAndDateDetail) {//timeDetail
        if (component == 0)
        {
            self.selectedYearRow = row;
        }
        else if (component == 1)
        {
            self.selectedMonthRow = row;
            [self.pickViewList reloadComponent:2];
        }
        else if (component == 2)
        {
            self.selectedDayRow = row;
        }
        else if (component == 3)
        {
            self.selectedHourRow = row;
        }
        else if (component == 4)
        {
            self.selectedMinRow = row;
        }
    }else if(tTypes == timeChinese){//timeChinese
        if (component == 0)
        {
            self.selectedDayRow = row;
        }
        else if (component == 1)
        {
            self.selectedHourRow = row;
        }
        else
        {
            self.selectedMinRow = row;
        }
    }else if (tTypes == dateDetail){//dateDetail
        if (component == 0)
        {
            self.selectedYearRow = row;
        }
        else if (component == 1)
        {
            self.selectedMonthRow = row;
            [self.pickViewList reloadComponent:2];
        }
        else if (component == 2)
        {
            self.selectedDayRow = row;
        }
    } else if (tTypes == timeDetail) {
        if (component == 0)
        {
           self.selectedHourRow = row;
        }
        else if (component == 1)
        {
            self.selectedMinRow = row;
        }
    } else {
        
    }
    
    [self.pickViewList reloadComponent:component];
}

#pragma mark -
#pragma mark - UIPickerViewDatasource

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)reusingView {
    
    // Custom View created for each component
    
    UILabel *pickerLabel = (UILabel *)reusingView;
    if (pickerLabel == nil) {
        CGRect frame = CGRectMake(0.0, 0.0, 60, 10);
        pickerLabel = [[UILabel alloc] initWithFrame:frame];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        pickerLabel.font = Font14;
        pickerLabel.textColor = RGBCOLORWITH16COLOR(0x333333);
    }
    
    if (tTypes==timeAndDateDetail) {//timeDetail
        
        if (component == 0)
        {
            pickerLabel.text =  [NSString stringWithFormat:@"%@年",[self.yearArray objectAtIndex:row]]; // Year
        }
        else if (component == 1)
        {
            pickerLabel.text = [NSString stringWithFormat:@"%@月",[self.monthArray objectAtIndex:row]];  // Month
        }
        else if (component == 2)
        {
            pickerLabel.text =  [NSString stringWithFormat:@"%@日",[self.daysArray objectAtIndex:row]]; // Date
            
        }
        else if (component == 3)
        {
            pickerLabel.text =  [NSString stringWithFormat:@"%@时",[self.hoursArray objectAtIndex:row]]; // Hours
        }
        else if (component == 4)
        {
            pickerLabel.text =  [NSString stringWithFormat:@"%@分",[self.minutesArray objectAtIndex:row]]; // Mins
        }
        
    }else if(tTypes == timeChinese){//timeChinese
        if (component == 0)
        {
            pickerLabel.text =  [self.daysArray objectAtIndex:row]; // Date
        }
        else if (component == 1)
        {
            pickerLabel.text =  [self.hoursArray objectAtIndex:row]; // Hours
        }
        else
        {
            pickerLabel.text =  [self.minutesArray objectAtIndex:row]; // Mins
        }
    }else if (tTypes == dateDetail){//dateDetail
        if (component == 0)
        {
            pickerLabel.text =  [NSString stringWithFormat:@"%@年",[self.yearArray objectAtIndex:row]]; // Year
        }
        else if (component == 1)
        {
            pickerLabel.text = [NSString stringWithFormat:@"%@月",[self.monthArray objectAtIndex:row]];  // Month
        }
        else if (component == 2)
        {
            pickerLabel.text =  [NSString stringWithFormat:@"%@日",[self.daysArray objectAtIndex:row]]; // Date
            
        }
    } else if (tTypes == timeDetail) {
        if (component == 0)
        {
            pickerLabel.text =  [NSString stringWithFormat:@"%@时",[self.hoursArray objectAtIndex:row]]; // hour
        }
        else if (component == 1)
        {
            pickerLabel.text = [NSString stringWithFormat:@"%@分",[self.minutesArray objectAtIndex:row]];  // minutes
        }

    } else {
        
    }
    
    return pickerLabel;
    
}


//返回组件数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    if (tTypes == timeAndDateDetail) {//timeDetail
        return 5;
    }else if(tTypes == timeChinese){
        return 3;
    }else if(tTypes == dateDetail){
        return 3;
    } else if (tTypes == timeDetail){
        return 2;//dateDetail
    } else {
        return 0;
    }
}

// returns the # of rows in each component..
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (tTypes == timeAndDateDetail) {//timeAndDateDetail
        if (component == 0)
        {
            return [self.yearArray count];
            
        }
        else if (component == 1)
        {
            return [self.monthArray count];
        }
        else if (component == 2)
        { // day
            if (self.selectedMonthRow == 0 || self.selectedMonthRow == 2 || self.selectedMonthRow == 4 || self.selectedMonthRow == 6 || self.selectedMonthRow == 7 || self.selectedMonthRow == 9 || self.selectedMonthRow == 11)
            {
                return 31;
            }
            else if (self.selectedMonthRow == 1)
            {
                int yearint = [[self.yearArray objectAtIndex:self.selectedYearRow]intValue ];
                
                if(((yearint %4==0)&&(yearint %100!=0))||(yearint %400==0)){
                    return 29;
                }
                else
                {
                    return 28; // or return 29
                }
            }
            else
            {
                return 30;
            }
        }
        else if (component == 3)
        { // hour
            return 24;
        }
        else
        { // min
            return 60;
        }
        
    }else if(tTypes == timeChinese){//timehinese
        if (component == 0)
        { // day
            return 3;
        }
        else if (component == 1)
        { // hour
            return 24;
        }
        else
        { // min
            return 60;
        }
    }else if (tTypes == dateDetail){//dateDetail
        if (component == 0)
        {
            return [self.yearArray count];
        }
        else if (component == 1)
        {
            return [self.monthArray count];
        }
        else
        { // day
            if (self.selectedMonthRow == 0 || self.selectedMonthRow == 2 || self.selectedMonthRow == 4 || self.selectedMonthRow == 6 || self.selectedMonthRow == 7 || self.selectedMonthRow == 9 || self.selectedMonthRow == 11)
            {
                return 31;
            }
            else if (self.selectedMonthRow == 1)
            {
                int yearint = [[self.yearArray objectAtIndex:self.selectedYearRow]intValue ];
                
                if(((yearint %4==0)&&(yearint %100!=0))||(yearint %400==0)){
                    return 29;
                }
                else
                {
                    return 28; // or return 29
                }
            }
            else
            {
                return 30;
            }
        }
    } else if (tTypes == timeDetail) {
    
        if (component == 0)
        {
            return [self.hoursArray count];
        }
        else
        {
            return [self.minutesArray count];
        }

    } else {
        return 0;
    }
}


#pragma mark -
#pragma mark - Others

// 选择完成
-(void)actionDone
{
    NSString *dateString = nil;
    NSDate *date = nil;
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    fm.locale = [NSLocale currentLocale];
    fm.timeZone = [NSTimeZone systemTimeZone];
        if (tTypes == timeAndDateDetail) {//timeDetail
           dateString = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",[self.yearArray objectAtIndex:[self.pickViewList selectedRowInComponent:0]],[self.monthArray objectAtIndex:[self.pickViewList selectedRowInComponent:1]],[self.daysArray objectAtIndex:[self.pickViewList selectedRowInComponent:2]],[self.hoursArray objectAtIndex:[self.pickViewList selectedRowInComponent:3]],[self.minutesArray objectAtIndex:[self.pickViewList selectedRowInComponent:4]]];
            fm.dateFormat = @"yyyy-MM-dd HH:mm";
            date = [fm dateFromString:dateString];
            
        }else if(tTypes == timeChinese){//timeChinese
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy年MM月dd日"];
            NSDate *todayDate=[formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
            NSTimeInterval secondsPerDay = 24 * 60 * 60;
            if ([[self.daysArray objectAtIndex:[self.pickViewList selectedRowInComponent:0]] isEqual:@"明天"]) {
                todayDate=[NSDate dateWithTimeInterval:secondsPerDay sinceDate:todayDate];
            }else if ([[self.daysArray objectAtIndex:[self.pickViewList selectedRowInComponent:0]] isEqual:@"后天"]) {
                todayDate=[NSDate dateWithTimeInterval:secondsPerDay*2 sinceDate:todayDate];
            }
            
            dateString = [NSString stringWithFormat:@"%@ %@%@",[formatter stringFromDate:todayDate],[self.hoursArray objectAtIndex:[self.pickViewList selectedRowInComponent:1]],[self.minutesArray objectAtIndex:[self.pickViewList selectedRowInComponent:2]]];
            
        }else if (tTypes == dateDetail) {
            dateString = [NSString stringWithFormat:@"%@-%@-%@",[self.yearArray objectAtIndex:[self.pickViewList selectedRowInComponent:0]],[self.monthArray objectAtIndex:[self.pickViewList selectedRowInComponent:1]],[self.daysArray objectAtIndex:[self.pickViewList selectedRowInComponent:2]]];
            fm.dateFormat = @"yyyy-MM-dd";
            date = [fm dateFromString:dateString];
            
        } else {
            dateString = [NSString stringWithFormat:@"%@:%@",[self.hoursArray objectAtIndex:[self.pickViewList selectedRowInComponent:0]],[self.minutesArray objectAtIndex:[self.pickViewList selectedRowInComponent:1]]];
            fm.dateFormat = @"HH:mm";
            date = [fm dateFromString:dateString];

        }
    if ([self.delegate respondsToSelector:@selector(datePickerView:selectDate:)]) {
        [self.delegate datePickerView:self selectDate:date];
    }
    [self hidePickerView];
}

// 取消选择
-(void)actionCancel
{
    [self hidePickerView];
}

// UIPicker隐藏
-(void)hidePickerView
{
    [self removeFromSuperview];
}

@end